package server

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"sanguo/cluster"
	"sanguo/node/node_dir"
	ss_msg "sanguo/protocol/ss/message"

	"github.com/golang/protobuf/proto"
	"github.com/sniperHW/kendynet"
)

var filePath_ string

func JsonParse(filePath string) {
	defer lockMap.Unlock()
	lockMap.Lock()

	filePath_ = filePath

	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		node_dir.Infoln("json readfile err:", err.Error())
		return
	}

	var serverList []*Server
	err = json.Unmarshal(data, &serverList)
	if err != nil {
		node_dir.Infoln("json Unmarshal :", err.Error())
		return
	}

	node_dir.Infoln(serverList)

	for _, v := range serverList {
		node_dir.Infoln(v)
		serverMap[int(v.ServerId)] = v
	}

	node_dir.Infoln("dir  JsonParse ok")
}

func onRefresh(session kendynet.StreamSession, msg proto.Message) {
	node_dir.Infoln("onRefresh")
	JsonParse(filePath_)
}

func init() {
	cluster.Register(&ss_msg.Refresh{}, onRefresh)
	go func() {
		http.HandleFunc("/config", func(w http.ResponseWriter, r *http.Request) {

			if r.Method == "POST" {
				str, err := ioutil.ReadAll(r.Body)
				if err != nil {
					node_dir.Infoln("Read failed:", err)
				}
				defer r.Body.Close()

				node_dir.Infoln("http Post:", string(str))
				switch string(str) {
				case "refresh":

					refresh := &ss_msg.Refresh{}
					cluster.Brocast("dir", refresh)
					w.Write([]byte("OK"))
				default:
					node_dir.Infoln("http Post, No this order:", string(str))
					w.Write([]byte("No this order"))
				}

			} else {

				node_dir.Infoln("ONly support Post")
				w.Write([]byte("Only support post"))
			}

		})

		err := http.ListenAndServe(":8000", nil)
		if err != nil {
			node_dir.Infoln("dir http err:", err)
		}
	}()

}
